package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPEchoServer {

    //Size of receive buffer
    private static final int BUFSIZE = 32;

    public static final int port = 9999;

    /**
     * @param args
     */
    public static void main(String[] args) {
        //Test for correct # of args
/*        if (args.length != 1) {
            throw new IllegalArgumentException("Parameter(s):<Port>");
        }*/
        int servPort = args.length > 0 ? Integer.parseInt(args[0]) : port;

        //Create a server socket to accept client connection request
        ServerSocket servSocket = null;
        int recvMsgSize = 0;
        byte[] receivBuf = new byte[BUFSIZE];

        try {
            servSocket = new ServerSocket(servPort);
            while (true) {
                Socket clientSocket = servSocket.accept();
                SocketAddress clientAddress = clientSocket.getRemoteSocketAddress();
                System.out.println("Handling client at " + clientAddress);

                InputStream in = clientSocket.getInputStream();
                OutputStream out = clientSocket.getOutputStream();

                //receive until client close connection,indicate by -l return
                while ((recvMsgSize = in.read(receivBuf)) != -1) {
                    String receivedData = new String(receivBuf, "utf-8");
                    System.out.println(receivedData);
                    out.write(receivBuf, 0, recvMsgSize);
                }
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}